<template>
    <div>
        <!--    面包屑导航区-->
        <el-breadcrumb separator="/">
            <el-breadcrumb-item :to="{ path: '/admin' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>分类管理</el-breadcrumb-item>
        </el-breadcrumb>

        <el-card shadow="never">
            <el-button type="primary" @click="createTypeDialogFormVisible = true">新建分类</el-button>

            <!-- 列表 -->
            <el-table :data="typeList" border stripe>
                <el-table-column type="index"></el-table-column>
                <el-table-column label="图片" prop="pic_url" width="150px">
                    <template slot-scope="scope">
                        <el-image :src="scope.row.picUrl"></el-image>
                    </template>
                </el-table-column>
                <el-table-column label="分类名称" prop="name"></el-table-column>
                <el-table-column label="博客数量" prop="count"></el-table-column>
                <el-table-column label="操作">
                    <template slot-scope="scope">
                        <!--            修改按钮-->
                        <el-button
                                type="primary"
                                icon="el-icon-edit-outline"
                                size="mini"
                                @click="editBlogDialog(scope.row)"
                        >编辑
                        </el-button>
                        <!--            删除按钮-->
                        <el-button
                                type="danger"
                                icon="el-icon-delete"
                                size="mini"
                                @click="removeBlogById(scope.row)"
                        >删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-card>

        <!-- 新建 、 修改，都会有的弹窗 -->
        <el-dialog :title="(createTypeForm.name!=='')?'分类修改':'分类创建'" :visible.sync="createTypeDialogFormVisible">
            <el-form style="text-align: left" ref="createTypeFormRef" :model="createTypeForm"
                     :rules="createTypeFormRules" label-width="80px">
                <el-form-item label="分类名称" prop="name">
                    <el-input v-model="createTypeForm.name"></el-input>
                </el-form-item>

                <el-form-item label="封面图片">
                    <!-- 图片上传区 -->
                    <el-upload
                            ref="upload"
                            action="#"
                            :http-request="uploadImg"
                            list-type="picture-card"
                            :limit="1"
                            :show-file-list="false"
                            :on-preview="handlePictureCardPreview"
                            :on-remove="handleRemove"
                            :on-success="handleSuccess">
                        <!-- 小图预览 -->
                        <img v-if="dialogImageUrl" :src="dialogImageUrl" class="preview">
                        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                    <!-- 大图预览 -->
                    <el-dialog :visible.sync="dialogVisible" :modal="false" style="top: auto" :before-close="reSelect">
                        <img width="100%" :src="dialogImageUrl" alt="">
                        <el-button type="primary" @click="reSelect">重新选择</el-button>
                        <el-button type="success" @click="confirmSelect">确定</el-button>
                    </el-dialog>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="backPage">取消</el-button>
                <el-button type="primary" @click="createType">提交</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
export default {
    data() {
        return {
            typeList: [],
            createTypeDialogFormVisible: false,
            updateTypeDialogFormVisible:false,
            dialogImageUrl:'',
            createTypeForm: {
                name: ''
            },
            createTypeFormRules: {
                name: [
                    {required: true, message: '分类名称不能为空', trigger: 'blur'}
                ],
            },
            newType: {
                id: '',
                name: '',
                picUrl: ''
            },
            fileList: [],
            dialogVisible: false,
            typeCountMap: new Map()
        }
    },
    created() {
        this.getFullTypeList();
    },
    methods: {

        compare(property) {
            return function (a, b) {
                let value1 = a[property].length;
                let value2 = b[property].length;
                return value2 - value1;
            }
        },
        // 得到所有的分类
        async getFullTypeList() {
            const {data: res} = await this.$basic.get('/type/allTypes')
            //console.log(res)
            this.typeList = res.data.typeList
            this.typeCountMap = res.data.typeCountMap
            for (let i in this.typeList){
                this.typeList[i].count = this.typeCountMap[this.typeList[i].id]
            }
        },

        selectCard(id) {
            this.selectedCard = id
            // console.log(this.selectedCard)
        },
        createType() {
            //表单信息里，只有 name
            //console.log(this.createTypeForm)
            this.$refs.createTypeFormRef.validate(async valid => {
                if (!valid) return
                //让后台根据 newType 有无 id 进行更新/新建
                this.newType.name = this.createTypeForm.name;
                this.newType.picUrl = this.dialogImageUrl;
                console.info(this.newType.id)
                const {data: res} = await this.$admin.post('/saveOrUpdateType',this.newType)
                if (res.code === 200) {
                    //console.log(this.newType)
                    this.createTypeDialogFormVisible = false
                    await this.getFullTypeList()
                    return this.$message.success("操作成功！")
                } else {
                    this.createTypeDialogFormVisible = false
                    return this.$message.error("操作失败！")
                }
            })
            this.backPage();
        },
        async removeBlogById(row) {
            //console.log(row.id)
            const {data: res} = await this.$admin.get(`/delType`,{
                params:{
                    id:row.id
                }
            })
            //console.log(res)

            if(res.code === 200){
                this.createTypeDialogFormVisible = false
                await this.getFullTypeList()
                return this.$message.success("操作成功！")
            }else {
                return this.$message.error("删除失败，请确认该类别下没有内容！")
            }
        },

        //确认选择图片
        confirmSelect(){
            this.dialogVisible=false;
        },
        //重新选择图片
        reSelect(){
            this.dialogImageUrl=null;
            this.dialogVisible=false;
        },

        async uploadImg(val){
            let fd = new FormData();
            fd.append('myfile',val.file)
            const{data:res} = await this.$basic.post('/upload',fd)
            let picName = res.data
            this.dialogImageUrl = 'http://localhost:8888/yumWebsite/avatar/'+picName
        },


        handleRemove() {
            this.dialogImageUrl = ''
        },
        handlePictureCardPreview(file) {
            this.dialogImageUrl = file.url;
            this.dialogVisible = true;
        },
        async handleSuccess(res) {
            this.$refs.upload.clearFiles();
            this.dialogVisible = true
        },

        backPage() {
            this.newType.id=null;
            this.newType.name='';
            this.newType.picUrl='';
            this.$refs.upload.clearFiles()
            this.createTypeDialogFormVisible = false
            this.createTypeForm.name = ''
            this.dialogImageUrl = ''
        },

        editBlogDialog(row) {
            this.newType.id = row.id;
            if (row.picUrl!=''){
                this.dialogImageUrl = row.picUrl
            }
            this.fileList = [{name: row.picUrl, url: row.picUrl}]
            this.createTypeForm.name = row.name
            this.createTypeDialogFormVisible = true
        }
    },
}
</script>

<style scoped>
    .preview {
        width: 100%;
        height: 100%;
        display: block;
    }
</style>
